package com.example.dishfo.myapplication.context;

import android.app.Application;
import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.LifecycleRegistry;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;

import com.example.dishfo.myapplication.context.casual.ComponentManager;
import com.example.dishfo.myapplication.dagger.component.DaggerServiceComponent;
import com.example.dishfo.myapplication.dagger.component.ServiceComponent;
import com.example.dishfo.myapplication.entity.User;

public class HoldApplication extends Application implements  UserHolding,ComponentManager{

    private User user;
    private String token;
    private volatile boolean isOnline=false;
    private ServiceComponent serviceComponent;


    @Override
    public void onCreate() {
        super.onCreate();
        serviceComponent= DaggerServiceComponent.create();
    }

    @Override
    public void loginCompete(User user, String token) {
        this.user=user;
        this.token=token;
        recordUser(user.getUserName(),user.getPassword());
        user.setPassword(null);
    }

    private final static String var_saveUser="saveUser";
    private final static String var_user="username";
    private final static String var_pwd="pwd";

    public User getSavedUser(){
        SharedPreferences preferences=getSharedPreferences(var_saveUser,MODE_PRIVATE);
        User user=new User();
        user.setUserName(preferences.getString(var_user,""));
        user.setPassword(preferences.getString(var_pwd,""));
        return user;
    }


    /**
     * 登陆成功时记录用户
     * //TODO 将对密码进行加密
     * @param user username
     * @param pwd pwd
     */
    private void recordUser(String user,String pwd){
        SharedPreferences preferences=
               getSharedPreferences(var_saveUser, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=preferences.edit();
        editor.putString(var_user,user);
        editor.putString(var_pwd,pwd);
        editor.apply();
    }


    @Override
    public void exit() {
        user=null;
        token=null;
    }

    @Override
    public User getUser() {
        return user;
    }

    @Override
    public ServiceComponent getServiceComponent() {
        return serviceComponent;
    }
}
